package cn.com.pajx.pajx_visitor_v3.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rcw.swiperefreshrecyclerview.OnItemClickListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedHashMap;
import java.util.List;

import butterknife.BindView;
import cn.com.pajx.pajx_visitor_v3.R;
import cn.com.pajx.pajx_visitor_v3.adapter.KeyboardAdapter;
import cn.com.pajx.pajx_visitor_v3.api.Api;
import cn.com.pajx.pajx_visitor_v3.base.BaseMvpActivity;
import cn.com.pajx.pajx_visitor_v3.bean.EventMessage;
import cn.com.pajx.pajx_visitor_v3.bean.KeyboardBean;
import cn.com.pajx.pajx_visitor_v3.mvp.presenter.LoadDataPresenterImpl;
import cn.com.pajx.pajx_visitor_v3.utils.AppConstant;
import cn.com.pajx.pajx_visitor_v3.utils.LocalDataUtil;
import cn.com.pajx.pajx_visitor_v3.utils.LogUtils;

/**
 * 拜访历史密码页面
 */
@SuppressLint("NonConstantResourceId")
public class QueryHistoryActivity extends BaseMvpActivity<LoadDataPresenterImpl> {

    @BindView(R.id.view_first)
    EditText viewFirst;
    @BindView(R.id.view_second)
    EditText viewSecond;
    @BindView(R.id.view_third)
    EditText viewThird;
    @BindView(R.id.view_four)
    EditText viewFour;
    @BindView(R.id.rv_keyboard)
    RecyclerView rvKeyboard;

    private EditText[] editTexts;
    private String key_word, school_name;
    private String school_id;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_query_history;
    }

    @Override
    protected LoadDataPresenterImpl initPresenter() {
        return new LoadDataPresenterImpl();
    }

    @Override
    protected void initView() {
        setHeadTitle("拜访历史");
        initDownTimer();
        editTexts = new EditText[]{viewFirst, viewSecond, viewThird, viewFour};
        //EditText事件监听
        initEditView();
        //初始化RecyclerView
        initRecyclerView();
    }

    /**
     * 隐藏系统软键盘
     */
    private void initEditView() {
        for (int i = 0; i < editTexts.length; i++) {
            int index = i;
            EditText viewInput = editTexts[index];
            hideSoftKeyboard(viewInput);
            viewInput.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.length() > 0 && index < editTexts.length - 1) {
                        editTexts[index + 1].requestFocus();
                    }
                }
            });
        }

        editTexts[0].requestFocus(); // 默认让第一个输入框获得焦点
    }

    private void hideSoftKeyboard(EditText viewInput) {
        viewInput.setShowSoftInputOnFocus(false);
        viewInput.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(viewInput.getWindowToken(), 0);

        });
    }

    /**
     * 初始化键盘的View
     */
    private void initRecyclerView() {
        if (rvKeyboard == null) return;
        List<KeyboardBean> keyboardBeans = LocalDataUtil.loadKeyboardBeans();
        rvKeyboard.setNestedScrollingEnabled(false);
        rvKeyboard.setLayoutManager(new GridLayoutManager(mContext, 3));
        KeyboardAdapter keyboardAdapter = new KeyboardAdapter(mContext, R.layout.keyboard_item, keyboardBeans);
        rvKeyboard.setAdapter(keyboardAdapter);
        keyboardAdapter.setOnItemClickListener(new OnItemClickListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void setOnClickListener(View view, int position) {
                resetDownTimer();
                keyboardAdapter.setSelection(position);
                KeyboardBean bean = keyboardBeans.get(position);
                switch (bean.getKey_code()) {
                    case "0"://数字
                        setEditData(bean);
                        break;
                    case "1"://删除
                        deleteEditData();
                        break;
                    case "2"://查询
                        checkPassword();
                        break;
                }

            }

            @Override
            public void setOnLongClickListener(View view, int position) {

            }
        });
    }

    /**
     * 删除
     */
    private void deleteEditData() {
        for (int i = 0; i < editTexts.length; i++) {
            EditText viewInput = editTexts[i];
            String value = viewInput.getText().toString().trim();
            LogUtils.e("value=" + value);
            if (viewInput.hasFocus()) {
                if (TextUtils.isEmpty(value)) {
                    if (i > 0) {
                        EditText viewPrevious = editTexts[i - 1];
                        viewPrevious.setText("");
                        viewPrevious.requestFocus();
                    }
                } else {
                    viewInput.setText("");
                }

                break;
            }
        }
    }

    /**
     * 设置数据
     *
     * @param bean 数据
     */
    private void setEditData(KeyboardBean bean) {
        for (EditText viewInput : editTexts) {
            String value = viewInput.getText().toString().trim();
            if (viewInput.hasFocus()) {
                viewInput.setText(bean.getKey());
                //将光标移至文字末尾
                viewInput.setSelection(viewInput.getText().length());
                break;
            }
        }
    }

    /**
     * 检验密码
     */
    private void checkPassword() {
        StringBuilder stringBuilder = new StringBuilder();
        for (EditText viewInput : editTexts) {
            String value = viewInput.getText().toString().trim();
            stringBuilder.append(value);
        }
        String password = stringBuilder.toString();
        LogUtils.e("password=" + password);
        LinkedHashMap<String, String> paramsMap = new LinkedHashMap<>();
        paramsMap.put("pw_query", password);
        mPresenter.loadData(Api.CHECK_QUERY_PASSWORD, paramsMap, "CHECK_QUERY_PASSWORD", "正在查询");
    }

    @Override
    public void onSuccess(String data, String aesKey, String message, int code, String tag) {
        super.onSuccess(data, aesKey, message, code, tag);
        Intent intent = new Intent(mContext, HistoryActivity.class);
        startActivity(intent);
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage bean) {
        if (TextUtils.equals(AppConstant.FRAGMENTDIALOG_DISMISS, bean.getMessage())) {
            resetDownTimer();
        }
    }

}